import time, json, os, datetime
from django.conf import settings
from django.shortcuts import render
from django.http import JsonResponse
from stock.models import PbcTradeDaily
from public import pbc_spider, pbc_dbtool
from public import pbc_tools, stock_tool, pub_tool


def index(request):
    if pub_tool.is_can_do('update_pbc_data', "09:22", count=2, interval_minute=240):
        # 每天9:22之后可以获取2次数据，每次间隔240分钟
        update_pbc_data()

    return render(request, template_name="stock/index.html")


def pbc(request):
    return render(request, template_name="stock/pbc.html")


def stock_view(request, stock_code):
    return render(request, template_name="stock/stock_view.html", context={"stock_code": stock_code})


def get_json_data(request, stock_code):
    stock_data = stock_tool.get_stock_data(stock_code)
    stock_workday_list = stock_tool.get_stock_workday_list(stock_data)
    pbc_data = pbc_tools.get_pbc_data(date_list=stock_workday_list, stock_code=stock_code)

    result_dict = {
        "data": stock_data["data"],
        "pbc": pbc_data
    }
    return JsonResponse(result_dict)


def get_pbc_json(request):
    return JsonResponse(pbc_tools.get_pbc_data())


def update_pbc_data():
    current_date = datetime.date.today()
    db_newest_data = PbcTradeDaily.objects.values('effective_date', 'content').order_by('effective_date').last()
    db_newest_effective_date = db_newest_data["effective_date"]
    db_newest_content = db_newest_data["content"]

    if db_newest_effective_date <= current_date:
        base_url = "http://www.pbc.gov.cn/zhengcehuobisi/125207/125213/125431/125475/17081/index{page}.html"
        page = 1

        pbc_spi = pbc_spider.PbcSpider()
        update_completed = False
        news_list = []
        for page in range(1, 3):
            if update_completed is True:
                break

            list_url = base_url.format(**{'page': page})
            urls = pbc_spi.get_url_list(list_url)

            for a_dict in urls:
                news = pbc_spi.get_news_detail(a_dict.get('href'))
                effective_date = datetime.datetime.strptime(news["DateTime"], "%Y-%m-%d %H:%M:%S").date()
                content = news["ZoomP"]
                if effective_date <= db_newest_effective_date or content == db_newest_content:
                    update_completed = True
                    break
                else:
                    news_list.append(news)
                    time.sleep(2)

        for news in reversed(news_list):
            print("body: ", news)
            pbc_dbtool.insert_one_pbctrade(news)

